<!-- eslint-disable ts/no-use-before-define -->
<script lang="ts" setup>
import type ProTable from '@/components/ProTable/index.vue'
import type { TableInstanceColumns } from '@/components/ProTable/type'
import { ClassInfoApi, CouponApi, OrderApi, StudentApi } from '@/apis'
import { useForm } from '@/hooks'
import getAvatar from '@/utils/avatar'
import { formatMoney } from '@/utils/common'
import ClassLessonPicker from '@/views/education/class/ClassLessonPicker.vue'
import ClassSelectPanel from '@/views/education/class/ClassSelectPanel.vue'
import ClassStatus from '@/views/education/class/components/ClassStatus.vue'
import { Message, Modal } from '@arco-design/web-vue'

defineOptions({
  name: 'OrderCreate',
})

const router = useRouter()
const route = useRoute()

const loading = ref(false)

// 订单信息
const { form, resetForm } = useForm<OrderApi.OrderCreateReq>({
  studentId: undefined,
  orderItemList: undefined,
  couponIdList: undefined,
  remark: undefined,
  remarkOut: undefined,
  payType: 'OFFLINE',
  sellerId: undefined,
})

// 学生信息
const studentInfo = ref<StudentApi.StudentDetailResp>()
const onStudentSelect = async (studentId) => {
  if (!studentId) {
    return
  }
  resetData()
  studentInfo.value = await StudentApi.getStudentDetail(studentId)
  getParentCouponList()
}

// 班级信息
const TableRef = ref<InstanceType<typeof ProTable>>()
const columns: TableInstanceColumns[] = [
  { title: '班级', slotName: 'name', fixed: 'left', width: 350 },
  { title: '年份科目', dataIndex: 'classYear', slotName: 'classYear', width: 150 },
  { title: '校区教室', dataIndex: 'classroomId', slotName: 'classroom', minWidth: 150, ellipsis: true, tooltip: true },
  { title: '状态', slotName: 'classStatus', minWidth: 120 },
  { title: '单价', dataIndex: 'unitPrice', slotName: 'unitPrice' },
  { title: '总价', dataIndex: 'totalPrice', slotName: 'totalPrice' },
  { title: '操作', width: 100, slotName: 'action' },
]
const expandable = {}
const orderClassList = ref<OrderApi.OrderClass[]>([])
const ClassSelectPanelRef = ref<InstanceType<typeof ClassSelectPanel>>()
const openClassSelect = () => {
  if (!studentInfo.value?.id) {
    return Message.warning('请选择学生')
  }
  ClassSelectPanelRef.value?.open()
}
const onOrderClassSelect = async (key, record) => {
  if (orderClassList.value.find(item => item.id === key)) {
    return Message.warning('已选择该班级')
  }
  const res = await ClassInfoApi.getClassLessonList({ classId: key })
  const lessonList = res.map(item => ({ ...item, selected: true }))
  const orderClass = { ...record, lessonList }
  orderClassList.value.push(orderClass)
  TableRef.value?.tableRef?.expandAll()
}
const onRemoveOrderClass = (record) => {
  const index = orderClassList.value.findIndex(item => item.id === record.id)
  orderClassList.value.splice(index, 1)
}

// 优惠信息
const couponList = ref<CouponApi.CouponDetail[]>([])
const selectedCouponIds = ref<string[]>([])
const getParentCouponList = async () => {
  if (!studentInfo.value?.parentId) {
    return
  }
  const query: CouponApi.ParentCouponQuery = {
    parentId: studentInfo.value.parentId,
    couponStatus: 1,
  }
  couponList.value = await CouponApi.getParentCouponList(query)
}
const onCouponClick = (coupon: CouponApi.CouponDetail) => {
  if (coupon.endValidTime) {
    if (new Date() >= new Date(coupon.endValidTime)) {
      return Message.error('优惠券已过期')
    }
  }
  if (!selectedCouponIds.value.includes(coupon.id)) {
    selectedCouponIds.value.push(coupon.id)
  } else {
    selectedCouponIds.value.splice(selectedCouponIds.value.findIndex(item => item === coupon.id), 1)
  }
}

// 算价格
const initOrderPriceDetail = () => {
  return {
    originalTotalPrice: 0,
    actualTotalPrice: 0,
    discountTotalPrice: 0,
    couponDiscountPrice: 0,
    packageDiscountPrice: 0,
    otherDiscountPrice: 0,
  }
}
const orderPriceDetail = ref<OrderApi.OrderPriceDetail>(initOrderPriceDetail())
watchEffect(async () => {
  if (studentInfo.value?.id && orderClassList.value.length > 0) {
    const data = {
      studentId: studentInfo.value?.id,
      couponIdList: selectedCouponIds.value,
      orderItemList: orderClassList.value.map(item => ({
        classId: item.id,
        lessonIndexes: item.lessonList.filter(lesson => lesson.selected).map(lesson => lesson.lessonIndex),
      })),
    }
    orderPriceDetail.value = await OrderApi.calculatePrice(data)
  }
})

const resetData = async () => {
  resetForm()
  studentInfo.value = undefined
  orderClassList.value = []
  couponList.value = []
  selectedCouponIds.value = []
  orderPriceDetail.value = initOrderPriceDetail()
}
watchEffect(() => {
  if (route.query.studentId) {
    onStudentSelect(route.query.studentId as string)
  }
})

// 提交订单
const onCreate = async () => {
  try {
    loading.value = true
    if (!studentInfo.value?.id) {
      return Message.error('请选择学生')
    }
    if (!orderClassList.value.length) {
      return Message.error('请添加选课')
    }
    if (!`${form.payType}`) {
      return Message.error('请选择支付方式')
    }
    form.studentId = studentInfo.value?.id
    form.couponIdList = selectedCouponIds.value
    form.payType = 'OFFLINE'
    form.orderItemList = orderClassList.value.map(item => ({
      classId: item.id,
      lessonIndexes: item.lessonList.filter(lesson => lesson.selected).map(lesson => lesson.lessonIndex),
    }))
    const orderId = await OrderApi.createOrder(form)
    Modal.success({
      title: '报名成功',
      content: '报名成功，请提醒家长缴费',
      okText: '查看订单',
      escToClose: false,
      onOk: () => {
        resetData()
        router.push({ path: '/shop/enrollment/order/detail', query: { id: orderId } })
      },
    })
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <ProPage class="flex-1 overflow-auto" title="创建订单" description="">
    <div class="flex gap-4">
      <div class="flex-[3]">
        <a-card title="报名学生" class="section">
          <template #extra>
            <StudentSelect class="min-w-260px" @select="onStudentSelect" />
          </template>
          <div class="flex gap-4">
            <a-image width="54" :src="getAvatar(studentInfo?.avatar, studentInfo?.gender)" />
            <div v-if="studentInfo">
              <div class="mb-3">
                <span class="font-size-16px font-600">{{ studentInfo.name }}</span>
                <icon-woman v-if="`${studentInfo.gender}` !== '1'" :size="16" :style="{ color: '#FF0088' }" />
                <icon-man v-else :size="16" :style="{ color: '#165DFF' }" />
              </div>
              <CellDict :value="studentInfo.enrollStatus" code="EnrollStatusEnum" />
            </div>
            <div class="ml-6 flex-1">
              <a-row>
                <a-col :span="8">
                  <span class="label">联系方式</span>
                  <span class="value">{{ studentInfo?.parentPhone }}</span>
                </a-col>
                <a-col :span="8">
                  <span class="label">出生年月</span>
                  <span class="value">{{ studentInfo?.birthdate?.substring(0, 7) || '-' }}</span>
                </a-col>
                <a-col :span="8">
                  <span class="label">入学年份</span>
                  <span class="value">{{ studentInfo?.admissionYear ? `${studentInfo.admissionYear}年` : '-' }}</span>
                </a-col>
              </a-row>
              <a-row class="mt-4">
                <a-col :span="8">
                  <span class="label">就读学校</span>
                  <span class="value">{{ studentInfo?.fulltimeSchool || '-' }}</span>
                </a-col>
                <a-col :span="8">
                  <span class="label">加入时间</span>
                  <span class="value">{{ studentInfo?.createTime || '-' }}</span>
                </a-col>
              </a-row>
            </div>
          </div>
        </a-card>
        <a-divider />
        <a-card title="报名班级" class="section">
          <template #extra>
            <a-button v-permission="['edu:class:read']" type="primary" @click="openClassSelect">
              <template #icon>
                <icon-plus />
              </template>
              <span>添加班级</span>
            </a-button>
          </template>
          <ProTable ref="TableRef" :data="orderClassList" :columns="columns" :loading="loading" :pagination="false" :expandable="expandable" default-expand-all-rows>
            <template #expand-row="{ record }">
              <ClassLessonPicker :lesson-list="record.lessonList" />
            </template>
            <template #name="{ record }">
              <CellClassInfo :id="record.id" :name="record.name" :lead-teacher-name="record.leadTeacherName" :assist-teacher-name="record.assistTeacherName" />
            </template>
            <template #classYear="{ record }">
              <DictLabel v-model="record.grade" code="Grade" /> · <DictLabel v-model="record.subject" code="Subject" />
              <div class="text-13px text-gray-4">
                {{ record.classYear }}年 · <DictLabel v-model="record.term" code="TermEnum" />
              </div>
            </template>
            <template #classroom="{ record }">
              <div>{{ record.classroomName || '-' }}</div>
              <div class="text-13px text-gray-4">
                {{ record.campusName }}
              </div>
            </template>
            <template #unitPrice="{ record }">
              {{ formatMoney(record.unitPrice) }}元/次
            </template>
            <template #totalPrice="{ record }">
              <div class="text-16px font-600">
                {{ formatMoney(record.lessonList.filter(item => item.selected).length * record.unitPrice) }}元
              </div>
              <span class="font-size-12px color-#165DFF">购{{ record.lessonList.filter(item => item.selected).length }}次</span>
            </template>
            <template #classStatus="{ record }">
              <ClassStatus code="ClassStatusEnum" :status="record.classStatus" />
            </template>
            <template #action="{ record }">
              <a-link status="danger" @click="onRemoveOrderClass(record)">
                移除
              </a-link>
            </template>
          </ProTable>
        </a-card>
        <a-card title="优惠券" class="section">
          <div v-if="couponList.length" class="mb-4 mt-4 flex flex-wrap gap-[15px]">
            <div v-for="(item, index) in couponList" :key="index" class="coupon-item" :class="{ active: selectedCouponIds.includes(item.id) }" @click="onCouponClick(item)">
              <div class="flex items-center justify-between">
                <div class="title color-black">
                  {{ item.template.name }}
                </div>
              </div>
              <div class="mt-2 text-13px">
                <span>有效期至</span>
                <span>{{ item.endValidTime }}</span>
              </div>
              <svg width="100%" height="25">
                <line x1="0" y1="15" x2="100%" y2="15" stroke="#cacdd3" stroke-width="1" stroke-dasharray="10, 5" />
              </svg>
              <a-space size="large">
                <div class="text-24px color-#FF7D00 font-600">
                  ￥{{ item.template.maxDiscountAmount }}
                </div>
                <div class="text-12px text-gray">
                  满￥{{ item.template.thresholdAmount }}使用
                  <div v-if="item.template.classIdLimit">
                    指定班级可用
                  </div>
                  <div v-if="item.template.classCategoryLimit">
                    指定班型可用
                  </div>
                  <div v-if="item.template.classSubjectLimit">
                    指定科目可用
                  </div>
                  <div v-if="item.template.classGradeLimit">
                    指定年级可用
                  </div>
                  <div v-if="!item.template.classIdLimit && !item.template.classCategoryLimit && !item.template.classSubjectLimit && !item.template.classGradeLimit">
                    无条件限制
                  </div>
                </div>
              </a-space>
            </div>
          </div>
          <a-empty v-else>
            没有可使用的优惠券
          </a-empty>
        </a-card>
        <a-divider />
        <a-card title="订单结算" class="section">
          <div class="order-info flex-row-between-start">
            <!-- <div>
              <span>明细:</span>
              <template v-if="orderClassList && orderClassList.length">
                <div v-for="(item, index) in orderClassList" :key="index" class="mt-xs">
                  <span class="mx-2 font-600">{{ index + 1 }}. {{ item.name }} </span>
                  <span class="">{{ item.unitPrice }}元/次 * {{ item.lessonList.filter(lesson => lesson.selected).length }}次 = {{ item.unitPrice * item.lessonList.filter(lesson => lesson.selected).length }}</span>
                </div>
              </template>
              <span v-else>-</span>
            </div> -->

            <a-space direction="vertical">
              <!-- <div class="flex-row-start-center">
                <span class="item-label">课程顾问</span>
                <EmployeeSelect v-model="form.sellerId" class="item-value" type="SELLER" placeholder="选择课程顾问" />
              </div> -->
              <div class="flex-row-start-center">
                <span class="item-label">内部备注：</span>
                <a-textarea v-model.trim="form.remark" class="item-value" placeholder="仅限员工内部查看" :max-length="255" show-word-limit />
              </div>
            </a-space>

            <a-space direction="vertical">
              <div class="flex-row-end-center text-align-right">
                <span class="w-100px">原价：</span>
                <span class="w-140px color-[#4E5969]">{{ formatMoney(orderPriceDetail.originalTotalPrice) }}</span>
              </div>
              <div class="flex-row-end-center text-align-right">
                <span class="w-100px">优惠券优惠：</span>
                <span class="w-140px text-align-right color-[#FF7D00]">-{{ formatMoney(orderPriceDetail.couponDiscountPrice) }}</span>
              </div>
              <div class="flex-row-end-center text-align-right">
                <span class="w-100px">其他优惠：</span>
                <span class="w-140px text-align-right color-[#FF7D00]">-{{ formatMoney(orderPriceDetail.otherDiscountPrice) }}</span>
              </div>
              <div class="flex-row-end-center text-align-right">
                <span class="w-100px">应付：</span>
                <span class="w-140px text-align-right font-size-20px color-[#F53F3F] font-600">{{ formatMoney(orderPriceDetail.actualTotalPrice) }}</span>
              </div>
            </a-space>
          </div>
        </a-card>
      </div>
    </div>
    <ClassSelectPanel ref="ClassSelectPanelRef" :student-id="studentInfo?.id" @select="onOrderClassSelect" />
    <div class="submit mt-4 flex justify-end bg-white px-6 py-3">
      <a-button v-permission="['shop:order:manage']" type="primary" :loading="loading" @click="onCreate">
        <template #icon>
          <icon-check />
        </template>
        <span>提交订单</span>
      </a-button>
    </div>
  </ProPage>
</template>

<style lang='less' scoped>
:deep(.arco-form-item-label-col) {
  padding-right: 10px;
  width: 50px;
}
:deep(.arco-page-header) {
  padding: 10px 0;
}
:deep(.pro-table-toolbar) {
  display: none;
}
.arco-divider {
  margin: 10px 0;
}
.label {
  display: inline-block;
  width: 80px;
  color: #888;
  flex-shrink: 0;
}
.value {
  color: #111;
}
.class-info {
  display: grid;
  grid-template-rows: repeat(4, 1fr);
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}
.lesson {
  :deep(.arco-card-body) {
    padding-top: 0 !important;
    background: #fff;
  }
}
:deep(.arco-card-body) {
  padding-top: 0 !important;
  background: #fff;
}

.coupon-item {
  box-sizing: border-box;
  background: #f5f7fd;
  padding: 10px;
  border-radius: 6px;
  width: calc(20% - 15px);
  border: 1px solid transparent;
  cursor: pointer;
  .title {
    position: relative;
    padding-left: 10px;
    font-size: 14px;
    font-weight: bold;
    &::before {
      position: absolute;
      content: '';
      width: 3px;
      height: 14px;
      border-radius: 2px;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      background: rgb(var(--primary-6));
    }
  }
  .arco-divider {
    margin: 10px 0;
  }
}

.active {
  border: 1px solid #fe840e;
  background: rgba(255, 125, 0, 0.1);
}

.order-info {
  padding: 20px;
  border-radius: 10px;
  background: #f5f7fd;

  .item-label {
    width: 100px;
    // color: var(--text-3, #86909c);
  }
  // .item-value {
  //   width: 240px;
  //   // color: var(--text-3, #86909c);
  // }
}
</style>
